package com.hopes.bizz.risk.activemq.config;

import com.hopes.bizz.risk.transfer.constant.RiskConstant;
import com.hopes.boss.common.core.constant.ActiveMqConstant;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.jms.client.ActiveMQQueue;
import org.apache.activemq.artemis.jms.client.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;

import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;

/**
 * @author daijie
 * @version 1.0
 * @date 2023/5/26 14:32
 * @Description:
 */
@Configuration
public class ActiveMQConfiguration {
    @Value("${activemq.url}")
    private String url;
    @Value("${activemq.user}")
    private String user;
    @Value("${activemq.password}")
    private String password;

    @Bean
    @ConditionalOnMissingBean(value = ConnectionFactory.class)
    public ConnectionFactory mqConnectionFactory() {
        // 必须暴露出来给Spring-boot，否则会抛出JMS health check错误
        return new ActiveMQConnectionFactory(url, user, password);
    }

    @Bean(name = "riskQueue")
    public Queue riskQueue() {
        return new ActiveMQQueue(RiskConstant.KEY_QUEUE_RISK);
    }

    @Bean(name = "tenantTopic")
    public Topic tenantTopic() {
        return new ActiveMQTopic(ActiveMqConstant.KEY_TOPIC_TENANT);
    }

    @Bean("topicListener")
    @ConditionalOnBean(ConnectionFactory.class)
    public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ConnectionFactory mqConnectionFactory) {
        final DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setConnectionFactory(mqConnectionFactory);
        bean.setPubSubDomain(true);
        return bean;
    }

    @Bean("queueListener")
    @ConditionalOnBean(ConnectionFactory.class)
    public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ConnectionFactory mqConnectionFactory) {
        final DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setConnectionFactory(mqConnectionFactory);
        return bean;
    }
}
